package com.garen.spring.web.client;

import com.garen.core.Endpoint;
import com.garen.core.Span;
import com.garen.spring.web.client.event.WebCollectEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * ClassName: WebCollectorFilter
 * Description:
 *
 * @author kang.wang03
 *         Date 16/9/8
 */
public class WebCollectorFilter implements Filter {
    private static final Log LOG = LogFactory.getLog(WebCollectorFilter.class);
    private String serviceName;
    private String packages;
    private CollectorServer collectorServer;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        serviceName = filterConfig.getInitParameter("serviceName");
        packages = filterConfig.getInitParameter("packages");
        collectorServer = new CollectorServer();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Map<String, Span> httpData = Collector.URL_DATA.get();
        if (httpData == null) {
            httpData = new HashMap<>();
        }
        Collector.URL_DATA.set(httpData);
        long startTime = System.currentTimeMillis();
        filterChain.doFilter(servletRequest, servletResponse);
        doMonitor(startTime, servletRequest, servletResponse);
    }

    private void doMonitor(long startTime, ServletRequest servletRequest, ServletResponse servletResponse) {
        Map<String, Span> webData = Collector.URL_DATA.get();
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            //请求返回的状态码
            int code = response.getStatus();
            //请求的总时间
            long totalTime = System.currentTimeMillis() - startTime;
            //请求url
            String url = request.getRequestURI();
            //数据长度
            LOG.info("request: " + url + " time:" + totalTime + "ms" + " status:" + code);
            Span span = new Span();
            span.setType(Span.SpanType.HTTP);
            span.setDuration(totalTime);
            span.setEndpoint(Endpoint.build()
                    .ipv4(getRemoteHost(request))
                    .serviceName(serviceName)
            );
            span.setTraceId(UUID.randomUUID().toString().replace("-", ""));
            webData.put(Collector.URL, span);

        } catch (Exception e) {
            LOG.warn("doMonitor", e);
        } finally {
            if (webData.get(Collector.URL) != null)
                CollectorServer.publishEvent(new WebCollectEvent(webData.get(Collector.URL)));
            Collector.URL_DATA.remove();
        }
    }

    public static String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    @Override
    public void destroy() {

    }
}
